package restfs

/*	GET /file/path
 *  PUT /file/path
 *  POST /file/path
 *  DELETE /file/path
 */

import (
	"code.google.com/p/cloud9lib/mongo"
	"code.google.com/p/cloud9lib/syncd/httpd"
	"io"
	"log"
	"net/http"
)

func getHandler(w http.ResponseWriter, req *http.Request) {

	name := req.URL.Path[4:]

	file, err := mongo.FS().Open(name)

	if err != nil {
		log.Println("restfs: not found: ", name)
		w.WriteHeader(404)
		return
	}

	w.Header().Set("Content-Type", file.ContentType())

	io.Copy(w, file)
}

func putHandler(w http.ResponseWriter, req *http.Request) {

	name := req.URL.Path[4:]

	file, err := mongo.FS().Create(name)

	if err != nil {
		log.Println("restfs: could not create file: ", name)
		w.WriteHeader(400)
		return
	}

	file.SetContentType(req.Header.Get("Content-Type"))
	io.Copy(file, req.Body)

	err = file.Close()

	if err != nil {
		log.Println("restfs: could not create file: close failed: ", name)
		w.WriteHeader(400)
		return
	}

	httpd.Publish("fs", "/fs/"+name)

	log.Println("restfs: new file uploaded: ", name)
}

func postHandler(w http.ResponseWriter, req *http.Request) {

	putHandler(w, req)
}

func deleteHandler(w http.ResponseWriter, req *http.Request) {

}

func Handler(w http.ResponseWriter, req *http.Request) {

	log.Println("restfs: ", req.Method, req.URL.String())

	switch req.Method {
	case "GET":
		getHandler(w, req)
	case "PUT":
		putHandler(w, req)
	case "POST":
		postHandler(w, req)
	case "DELETE":
		deleteHandler(w, req)
	default:
		w.WriteHeader(400)
	}
}
